#include "search.h"
#include "ui_search.h"

#include <QNetworkReply>


Search::Search(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::search)
{
    ui->setupUi(this);
    softKeyboard = new SoftKeyboard();
    ui->lineEdit->installEventFilter(this);

    networkManager = new QNetworkAccessManager(this);
    connect(networkManager, &QNetworkAccessManager::finished, this, &Search::Received);

}


Search::~Search()
{
    delete ui;
}
//事件过滤器处理函数
bool Search::eventFilter(QObject *watched, QEvent *event)
{
    //添加键盘
    if(event->type()==QEvent::MouseButtonRelease)//事件类型
    {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);//将事件强制转换
        if(mouseEvent->button() == Qt::LeftButton)
        {
            QPoint point = this->pos();
            if(watched == ui->lineEdit)
            {
                softKeyboard->hideInputBufferArea(ui->lineEdit);
                softKeyboard->resize(600,320);
                // 获取lineEdit的全局位置
                QPoint lineEditGlobalPos = ui->lineEdit->mapToGlobal(QPoint(0, 0));
                // 计算softKeyboard的顶部位置
                int newY = lineEditGlobalPos.y() +ui->lineEdit->height();
                // 移动softKeyboard到lineEdit的上方
                softKeyboard->move(point.x() + (this->width() - 600) / 2, newY);
                softKeyboard->setMoveEnabled(false);
                softKeyboard->show();
            }
        }
    }
    return QMainWindow::eventFilter(watched,event);//返回父类的事件过滤器
}

//查询车位
void Search::on_SearchButton_clicked()
{
    //发送记录请求查询
    QString  mapUrl = "http://192.168.1.117:8080/api/records";

    QUrl url(mapUrl);
    QUrlQuery query;
    if(ui->lineEdit->text().isEmpty())
    {
          QMessageBox::warning(this,"警告","请输入车牌号");
    }
    else
    {
        query.addQueryItem("license_plate", ui->lineEdit->text());
        //执行命令
        url.setQuery(query);
        QNetworkRequest request(url);
        networkManager->get(request);
    }
}

void Search::on_backButton_clicked()
{
    this->parentWidget()->show();
    this->close();
}

void Search::Received(QNetworkReply * reply)
{

    if (reply->error() == QNetworkReply::NoError)
    {
        QByteArray Data = reply->readAll();
        qDebug() << "完整的响应内容: " << QString::fromUtf8(Data);
        QJsonParseError jsonerror;
        QJsonDocument doc = QJsonDocument::fromJson(Data, &jsonerror);
        if(jsonerror.error != QJsonParseError::NoError) //判断是否json格式错误
        {
             qDebug()<<"json error";
        }

        //把doc转对象
        QJsonObject obj = doc.object();
        int  count = obj.value("count").toInt();
        qDebug() << "Count:" << count;

        status = 0;
        row = 0;
        //如果是历史查询
        if (obj.contains("records") && obj["records"].isArray())
        {
            QJsonArray records = obj["records"].toArray();
            // 遍历records数组
             for (const QJsonValue &recordValue : records)
             {
                 row++;
                 if (recordValue.isObject())
                 {
                     QJsonObject recordObj = recordValue.toObject();
                     if(recordObj.value("curr_status").toInt()==1)
                     {
                         qDebug()<<"我在";
                        // 提取记录中的字段
                        ui->parkingSpotLineEdit->setText(recordObj.value("spot_id").toString());
                        qint64 in_time = recordObj.value("enter_time").toString().toLongLong();
                        QDateTime indatetime;
                        indatetime= QDateTime::fromTime_t(static_cast<time_t>(in_time));
                        QString  m_intime = indatetime.toString("yyyy-MM-dd HH:mm:ss");
                        ui->entryTimeLineEdit->setText(m_intime);
                        status =recordObj.value("curr_status").toInt();
                    }

                 }
             }
             if(status == 0)
             {
                QMessageBox::warning(this,"finderror","车已不在库中");
             }

        }

    }
    //获取数据失败
    else
    {
        QMessageBox::warning(this,"finderror","查找失败");
        qDebug() << "错误: " << reply->errorString();
        qDebug() << "响应: " << reply->readAll();
    }

    if(row==0)
    {
        QMessageBox::warning(this,"finderror","没找到数据");
    }



    //清空缓存区
    reply->deleteLater();
}
